<?php


namespace app\http\middleware;


use app\admin\model\Staff;
use app\admin\model\StaffTime;
use app\admin\model\Token;
use app\sys\model\Fun;
use app\sys\model\Role;
use app\sys\model\RoleLog;
use think\facade\Request;

class checkToken
{
    public function handle($request, \Closure $next)
    {
        $token = Request::header('token');
        if (empty($token)) {
            return failedJson("请传入正确Token", 2);
        }
        //token验证通过
        try {
            $device_type = get_device_type();
            $device_id = Request::header("user-agent");
            $token_info = Token::where("token", $token)
                ->where("device_type", $device_type)
                ->find();
            if (empty($token_info)) {
                return failedJson("Token无效.", 2);
            }
            $t = $token_info["expire_time"] - time();
            if ($t <= 0) {
                $token_info->delete();
                return failedJson("Token已过期.", 2);
            }
            if ($token_info["device_id"] != $device_id){
                return failedJson("已在其他设备登录.如非本人操作,请更换密码", 2);
            }
            $token_info->isUpdate(true)->save([
                "expire_time" => strtotime("+5 hour"),
            ]);

            list($res,$info) = Staff::GetInfo($token_info["staff_no"]);
            if($res == "err")return failedJson($info, 1, $info);

            $request->_user = $info;
            // 客服操作时长
//            StaffTime::saveTime($token_info["staff_no"],$request->_user);
            return $next($request);
        } catch (\Exception $e) {
            return failedJson("内部错误", 1, $e->getMessage());
        }
    }



}